package com.example.senior_homework.repository.web

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object AppGson {

    private const val DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"

    fun create(): Gson {
        return GsonBuilder()
            .setLenient()
            .registerTypeAdapter(Date::class.java, DateTypeAdapter())
            .create()
    }

    private class DateTypeAdapter : TypeAdapter<Date>() {

        private val dateFormat = SimpleDateFormat(DATE_FORMAT, Locale.getDefault())

        override fun write(out: JsonWriter, value: Date?) {
            if (value == null) {
                out.nullValue()
            } else {
                out.value(dateFormat.format(value))
            }
        }

        override fun read(`in`: JsonReader): Date? {
            return try {
                dateFormat.parse(`in`.nextString())
            } catch (e: ParseException) {
                throw IOException(e)
            }
        }
    }
}